package com.cskaoyan.order.biz.handler;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.exception.BaseBusinessException;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.order.biz.context.AbsTransHandlerContext;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

    @Autowired
    StockMapper stockMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    @Transactional
    public boolean handle(TransHandlerContext context) {
        /*TODO:扣减 购物车中，被选中成为订单中商品 的库存*/

        // 让 TransHandlerContext对象context 向下转型为 CreateOrderContext
        CreateOrderContext createOrderContext = (CreateOrderContext) context;
        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();


        /*遍历 cartProductDtoList ，让每个productId商品的库存更改productNum*/
        for (CartProductDto dto : cartProductDtoList) {
            Long productId = dto.getProductId();
            Long productNum = dto.getProductNum();

            Stock stock = new Stock();
            stock.setItemId(productId);
            // 被锁定的库存量应加上 productNum
            stock.setLockCount(productNum.intValue());
            /*因为 sql语句 中是
            * stock_count = stock_count + #{stockCount}
            * 来修改 当前商品的库存量 的。
            * 而 当前商品的库存量 应减去 productNum ，所以传入 -productNum */
            stock.setStockCount(-productNum);

            stockMapper.updateStock(stock);
        }

        return true;
    }
}